package com.usian.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.usian.mapper.*;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.utils.IDUtils;
import com.usian.utils.PageResult;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemService {

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private TbItemDescMapper tbItemDescMapper;

    @Autowired
    private TbItemParamMapper tbItemParamMapper;

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Autowired
    private TbItemParamItemMapper tbItemParamItemMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RedisClient redisClient;

    @Value("${ITEM_INFO}")
    private String ITEM_INFO;

    @Value("${BASE}")
    private String BASE;

    @Value("${DESC}")
    private String DESC;

    @Value("${PARAM}")
    private String PARAM;

    @Value("${ITEM_INFO_EXPIRE}")
    private Integer ITEM_INFO_EXPIRE;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    public TbItem selectItemInfo(Long itemId) {
        return tbItemMapper.selectByPrimaryKey(itemId);
    }

    public PageResult selectTbItemAllByPage(Integer page, Integer rows) {
        //开启分页
        PageHelper.startPage(page,rows);
        List<TbItem> list = tbItemMapper.findAll();
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        //返回pageResult
        PageResult pageResult = new PageResult();
        pageResult.setResult(pageInfo.getList());
        pageResult.setTotalPage(Long.valueOf(pageInfo.getPages()));
        pageResult.setPageIndex(pageInfo.getPageNum());
        return pageResult;
    }

    /**
     * 添加
     */
    public Integer insertTbItem(TbItem tbItem, String desc, String itemParams) {
        //添加商品基本信息
        //补齐Tbitem数据  雪花算法
        long id = IDUtils.genItemId();
        Date date = new Date();
        tbItem.setUpdated(date);
        tbItem.setCreated(date);
        tbItem.setId(id);
        //逻辑删除
        tbItem.setStatus((byte)1);
        int i1 = tbItemMapper.insertSelective(tbItem);

        //添加商品描述
        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setUpdated(date);
        tbItemDesc.setCreated(date);
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(desc);
        int i2 = tbItemDescMapper.insertSelective(tbItemDesc);

        //添加商品规格参数
        TbItemParamItem tbItemParamItem = new TbItemParamItem();
        tbItemParamItem.setItemId(id);
        tbItemParamItem.setParamData(itemParams);
        tbItemParamItem.setUpdated(date);
        tbItemParamItem.setCreated(date);
        int i3 = tbItemParamItemMapper.insertSelective(tbItemParamItem);

        //添加商品发布消息到mq
        amqpTemplate.convertAndSend("item_exchage","item.add", id);

        return i1+i2+i3;
    }


    /**
     * 根据商品 ID 查询商品，商品分类，商品描述，商品规格参数

     */
    public Map<String, Object> preUpdateItem(Long itemId) {
        Map<String,Object> map = new HashMap<>();
        //根据商品id查询商品
        TbItem item = tbItemMapper.selectByPrimaryKey(itemId);
        map.put("item",item);
        //根据商品id查询商品描述
        TbItemDesc itemDesc = tbItemDescMapper.selectByPrimaryKey(itemId);
        map.put("itemDesc",itemDesc.getItemDesc());
        //根据商品id查询商品类目（分类）
        TbItemCat itemCat = tbItemCatMapper.selectByPrimaryKey(item.getCid());
        map.put("itemCat",itemCat.getName());
        //根据商品id查询商品规格信息
        List<TbItemParamItem> list = tbItemParamItemMapper.selectByItemId(itemId);
        map.put("itemParamItem",list.get(0).getParamData());
        return map;
    }


    /**
     * 修改
     */
    public Integer updateTbItem(TbItem tbItem, String desc, String itemParams) {
        //修改商品基本信息
        //补齐Tbitem数据  雪花算法
        long id = IDUtils.genItemId();
        Date date = new Date();
        int i1 = tbItemMapper.updateByPrimaryKeySelective(tbItem);

        //修改商品描述
        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(tbItem.getId());
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setUpdated(date);
        tbItemDesc.setCreated(date);
        int i2 = tbItemDescMapper.updateByPrimaryKeySelective(tbItemDesc);

        //修改商品规格参数
        TbItemParamItem tbItemParamItem = new TbItemParamItem();
        tbItemParamItem.setParamData(itemParams);
        tbItemParamItem.setUpdated(date);
        tbItemParamItem.setCreated(date);

        TbItemParamItemExample tbItemParamItemExample = new TbItemParamItemExample();
        TbItemParamItemExample.Criteria criteria = tbItemParamItemExample.createCriteria();
        criteria.andItemIdEqualTo(tbItem.getId());
        int i3 = tbItemParamItemMapper.updateByExampleSelective(tbItemParamItem,tbItemParamItemExample);

        //添加商品发布消息到mq
        amqpTemplate.convertAndSend("item_exchage","item.updateItem", id);
        return i1+i2+i3;
    }

    /**
     * 删除
     */
    public Integer deleteItemById(Long itemId) {
        long id = IDUtils.genItemId();
        TbItem tbItem = tbItemMapper.selectByPrimaryKey(itemId);
        tbItem.setStatus((byte)2);
        tbItem.setUpdated(new Date());
        tbItem.setCreated(new Date());
        //添加商品发布消息到mq
        amqpTemplate.convertAndSend("a","item.deleteItem", id);
        return tbItemMapper.updateByPrimaryKeySelective(tbItem);
    }


    /**
     * 添加商品规格模板
     *
     */
    public Integer insertItemParam(Long itemCatId, String paramData) {
        //判断该类别的商品是否有规格模板
        TbItemParamExample tbItemParamExample = new TbItemParamExample();
        TbItemParamExample.Criteria criteria = tbItemParamExample.createCriteria();
        criteria.andItemCatIdEqualTo(itemCatId);
        List<TbItemParam> itemParamList = tbItemParamMapper.selectByExample(tbItemParamExample);
        if (itemParamList.size()>0){
            return 0;
        }

        //保存规格模板
        Date date = new Date();
        TbItemParam tbItemParam = new TbItemParam();
        tbItemParam.setItemCatId(itemCatId);
        tbItemParam.setParamData(paramData);
        tbItemParam.setUpdated(date);
        tbItemParam.setCreated(date);
        return tbItemParamMapper.insertSelective(tbItemParam);
    }

    /**
     * 查询所有商品规格模板
     */
    public PageResult selectItemParamAll(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        TbItemParamExample example = new TbItemParamExample();
        List<TbItemParam> list = tbItemParamMapper.selectByExampleWithBLOBs(example);
        PageInfo<TbItemParam> pageInfo = new PageInfo<>(list);
        PageResult pageResult = new PageResult();
        pageResult.setPageIndex(page);
        pageResult.setResult(pageInfo.getList());
        pageResult.setTotalPage(Long.valueOf(pageInfo.getPages()));
        return pageResult;
    }

    public Integer deleteItemParamById(Long id) {
       return tbItemParamMapper.deleteByPrimaryKey(id);
    }

    public TbItem selectItemInfoRedis(Long itemId) {
        TbItem tbItem = (TbItem) redisClient.get(ITEM_INFO + ":" + itemId);

        if (tbItem != null){
            return tbItem;
        }
        TbItem tbi = tbItemMapper.selectByPrimaryKey(itemId);
        redisClient.set(ITEM_INFO + ":" + itemId,tbi);
        redisClient.expire(ITEM_INFO + ":" + itemId,ITEM_INFO_EXPIRE);
        return  tbi;
    }

    public TbItemDesc selectItemDescByItemId(long itemId) {
        TbItemDesc tbItemDesc = tbItemDescMapper.selectByPrimaryKey(itemId);
        redisClient.set(ITEM_INFO+":"+DESC,tbItemDesc);
        redisClient.expire(ITEM_INFO + ":" + BASE,ITEM_INFO_EXPIRE);
        return tbItemDesc;
    }

    public Integer updateTbItemByOrderId(String msg) {
        //扣减库存的公式  num = 原来商品的num - 订单中商品的num
        List<TbOrderItem> list = tbOrderItemMapper.selectByOrderId(msg);
        Integer count = 0;
        for (TbOrderItem tbOrderItem : list) {
            TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.parseLong(tbOrderItem.getItemId()));
            //商品原有的库存数量
            Integer numY = tbItem.getNum();
            //订单中商品的数量
            Integer numX = tbOrderItem.getNum();
            //扣减库存的商品数量
            Integer num =  numY-numX;
            //库存数量不能小于0 否则报错
            if (num<0){
                throw new RuntimeException("扣减失败");
            }
            tbItem.setNum(num);
            int i = tbItemMapper.updateByPrimaryKey(tbItem);
            count+=i; //cout = count+i
        }
         return count;
    }

    public Integer updateDelTbItemByOrderId(String msg) {
        List<TbOrderItem> list = tbOrderItemMapper.selectByOrderId(msg);
        Integer count = 0;
        for (TbOrderItem tbOrderItem : list) {
            TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.parseLong(tbOrderItem.getItemId()));
            //商品原有的库存数量
            Integer numY = tbItem.getNum();
            //订单中商品的数量
            Integer numX = tbOrderItem.getNum();
            //加回库存的商品数量
            Integer num =  numY+numX;
            tbItem.setNum(num);
            int i = tbItemMapper.updateByPrimaryKey(tbItem);
            count+=i; //cout = count+i
        }
        return count;
    }
}
